package board.command;

import java.awt.*;
import java.util.*;

import board.Board;

import sgf.SGFParseException;
import sgf.SGFUtils;

/**
 * Represents a move on the Board.
 * @author TKington
 *
 */
public class MoveCommand extends Command {
	/** The player making a move - 1 for black, -1 for white. */
    private int player;
    /** The x,y location of the move. */
    private Point move;
    /** Used to remember stones that were captured by the move, and
     * must be replaced on undo.
     */
    private AddCommand replaceStones;
    /** Used to remember the ko point before the move for undo. */
    private Point oldKoPoint;
    
    /**
     * Creates a new MoveCommand.
     * @param p the current player - 1 for black, -1 for white
     * @param props the SGF properties of the move
     * @throws SGFParseException if the properties are illegal
     */
    public MoveCommand(int p, ArrayList props) throws SGFParseException {
        player = p;
        move = SGFUtils.stringToPoint((String)props.get(0));
    }
    
    /**
     * Creates a MoveCommand.
     * @param p the current player - 1 for black, -1 for white
     * @param pos the x,y location of the move
     */
    public MoveCommand(int p, Point pos) {
        player = p;
        move = pos;
    }
    
    @Override
	public boolean doIt(Board b) {
        ArrayList<Point> capturedStones = new ArrayList<Point>();
        
        oldKoPoint = (Point)b.getKoPoint().clone();
        
        b.move(player, move.x, move.y, capturedStones);
        if(!capturedStones.isEmpty()) {
            replaceStones = new AddCommand(player * -1);
            replaceStones.setPoints(capturedStones);
        }
        return true;
    }
    
    @Override
	public void undoIt(Board b) {
        if(replaceStones != null) {
            replaceStones.doIt(b);
        }
        
        b.remove(move.x, move.y);
        b.setKoPoint(oldKoPoint);
    }
    
    @Override
	public Rectangle getBounds() { return new Rectangle(move); }
    
    @Override
	public void validatePoints(int size) throws SGFParseException {
        SGFUtils.checkPoint(move, size);
    }
    
    /**
     * Returns the color of the move.
     * @return 1 for black, -1 for white
     */
    public int getPlayer() { return player; }
    
    /**
     * Returns the x,y location of the move.
     * @return the x,y location
     */
    public Point getPoint() { return move; }
    
    @Override
	public boolean equals(Object o) {
    	if(!(o instanceof MoveCommand))
    		return false;
    	
    	MoveCommand c = (MoveCommand)o;
    	if(!move.equals(c.move))
    		return false;
    	if(player != c.player)
    		return false;
    	return true;
    }
}
